package requestmgr

import (
	"context"
	"fmt"
	"math/rand"
	"testing"

	vulnReqCache "github.com/stackrox/rox/central/vulnmgmt/vulnerabilityrequest/cache"
	vulnReqDS "github.com/stackrox/rox/central/vulnmgmt/vulnerabilityrequest/datastore"
	"github.com/stackrox/rox/pkg/fixtures"
	"github.com/stackrox/rox/pkg/postgres/pgtest"
	"github.com/stackrox/rox/pkg/sac"
	"github.com/stretchr/testify/assert"
)

func BenchmarkCreate(b *testing.B) {
	testDB := *pgtest.ForT(b)

	pendingCache, activeCache := vulnReqCache.New(), vulnReqCache.New()
	vulnReqDataStore, err := vulnReqDS.GetTestPostgresDataStore(b, testDB, pendingCache, activeCache)
	assert.NoError(b, err)

	ctx := sac.WithAllAccess(context.Background())
	numExistingReqs := 10000
	for i := 0; i < numExistingReqs; i++ {
		req := fixtures.GetImageScopeDeferralRequest("registry", "remote", fmt.Sprintf("%d", i), "cve-2023-xyz")
		err := vulnReqDataStore.AddRequest(ctx, req)
		assert.NoError(b, err)
	}

	manager := New(nil, vulnReqDataStore, pendingCache, nil, nil, nil, nil, nil, nil, nil)

	b.Run("create", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			tag := fmt.Sprintf("%d", rand.Intn(numExistingReqs))
			req := fixtures.GetImageScopeDeferralRequest("registry", "remote", tag, "cve-2023-xyz")
			req.Id = ""

			assert.NoError(b, manager.Create(ctx, req))
		}
	})
}
